package com.bwie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.bwie.service.UserService;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.ForgotVo;
import com.bwie.vo.RegisterVo;
import com.bwie.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @program: day0808
 * @author: 枉度生
 * @description:
 * @create: 2025-08-08 09:51
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private boolean isMobile(String mobile){
        String s="^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
        return ReUtil.isMatch(s,mobile);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public R UserLogin(@RequestBody UserVo userVo){
        return userService.UserLogin(userVo);
    }

    @PostMapping("/sendCode/{mobile}")
    @ApiOperation("发送验证码")
    public R sendCode(@PathVariable(name = "mobile") String mobile){

        if (!isMobile(mobile)){
            return R.ERROR(400,"手机号格式错误");
        }
        //随机数
        RandomUtil randomUtil = new RandomUtil();
        //设置为6位
        String code = randomUtil.randomNumbers(6);
        //发送短信
        MobileMessageUtil.sendMobileMessage(mobile,code);
        //存入缓存
        stringRedisTemplate.opsForValue().set("code:"+mobile,code,5, TimeUnit.MINUTES);
        //后台输出
        System.out.println(code);
        return R.OK(code);

    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public R register(@Validated @RequestBody RegisterVo registerVo){
        return userService.register(registerVo);
    }

    @PostMapping("/forgotPassword")
    @ApiOperation("忘记密码")
    public R forgotPassword(@Validated @RequestBody ForgotVo forgotVo){
        return userService.ForgotPassword(forgotVo);
    }
}
